// API基础URL，确保与后端服务端口一致
const API_BASE_URL = 'http://localhost:8080/api/auth';
const LOG_API_BASE_URL = 'http://localhost:8080/api/logs';

// API端点配置
const api = {
  // 认证相关API
  login: `${API_BASE_URL}/login`,
  register: `${API_BASE_URL}/register`,
  me: `${API_BASE_URL}/me`,
  changePassword: `${API_BASE_URL}/change-password`,
  
  // 用户管理相关API
  deleteUser: (userId) => `${API_BASE_URL}/admin/users/${encodeURIComponent(userId)}`,
  updateUser: (userId) => `${API_BASE_URL}/admin/users/${encodeURIComponent(userId)}`,
  resetPassword: (userId) => `${API_BASE_URL}/admin/users/${encodeURIComponent(userId)}/password`,
  searchUsers: `${API_BASE_URL}/admin/users/search`,
  createUser: `${API_BASE_URL}/admin/users`,
  listUsers: `${API_BASE_URL}/admin/users`,
  
  // 日志相关API
  queryLogs: `${LOG_API_BASE_URL}/query`,
  getLogById: (id) => `${LOG_API_BASE_URL}/${encodeURIComponent(id)}`,
  getLogsByRequestId: (requestId) => `${LOG_API_BASE_URL}/request/${encodeURIComponent(requestId)}`,
  getLogStats: `${LOG_API_BASE_URL}/stats`,
  getLogTrend: `${LOG_API_BASE_URL}/trend`,
};

// 全局token变量
let token = '';

// HTTP请求工具函数
// 修改request函数，添加更详细的日志
async function request(url, options = {}) {
  const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
    console.log('[DEBUG] 请求头中添加token:', (token || '').substring(0, 10) + '...');
  }
  
  try {
    console.log('[DEBUG] 请求URL:', url);
    console.log('[DEBUG] 请求方法:', options.method || 'GET');
    console.log('[DEBUG] 请求头:', JSON.stringify(headers));
    console.log('[DEBUG] 请求体:', options.body);
    
    const res = await fetch(url, { ...options, headers });
    
    console.log('[DEBUG] 响应状态码:', res.status);
    
    const text = await res.text();
    console.log('[DEBUG] 原始响应内容:', text);
    
    let data;
    try { data = JSON.parse(text); } catch (e) { data = text; }
    
    console.log('[DEBUG] 解析后响应数据:', JSON.stringify(data));
    
    // 添加到调试面板
    addDebugInfo({
      url: url,
      method: options.method || 'GET',
      headers: headers,
      body: options.body,
      response: {
        status: res.status,
        data: data
      },
      timestamp: new Date().toISOString()
    });
    
    return { ok: res.ok, status: res.status, data };
  } catch (error) {
    console.error('[DEBUG] 请求异常:', error);
    
    // 添加错误信息到调试面板
    addDebugInfo({
      url: url,
      method: options.method || 'GET',
      headers: headers,
      body: options.body,
      error: error.message,
      timestamp: new Date().toISOString()
    });
    
    return { ok: false, status: 0, data: { success: false, message: '网络错误: ' + error.message } };
  }
}

// 显示结果的工具函数
function showResult(elementId, response, isSuccess = false) {
  const element = document.getElementById(elementId);
  if (response && typeof response === 'object') {
    element.textContent = JSON.stringify(response, null, 2);
    element.className = isSuccess ? 'success' : 'error';
  } else {
    element.textContent = response;
    element.className = isSuccess ? 'success' : 'error';
  }
}

// 保存token到localStorage
function saveToken(newToken, rememberMe = false) {
  // 如果传入了token参数，使用它；否则使用全局token变量
  if (newToken) {
    token = newToken;
    window.token = newToken;
  } else if (token) {
    window.token = token;
  }
  
  // 保存到localStorage
  if (token) {
    console.log('Saving token to storage:', token);
    if (rememberMe) {
      // 记住密码时，设置长期存储
      localStorage.setItem('auth_token', token);
      localStorage.setItem('remember_me', 'true');
    } else {
      // 不记住密码时，设置会话存储
      sessionStorage.setItem('auth_token', token);
      // 只有在记住密码被选中过的情况下才清除localStorage中的remember_me标记
      if (localStorage.getItem('remember_me') === 'true') {
        localStorage.removeItem('auth_token');
      }
      // 但不移除remember_me标记，因为用户可能之前选择了记住密码
    }
    return true;
  }
  return false;
}

// 从localStorage加载token
function loadToken() {
  // 检查是否需要记住密码
  const rememberMe = localStorage.getItem('remember_me') === 'true';
  
  let savedToken;
  if (rememberMe) {
    // 从localStorage加载（长期存储）
    savedToken = localStorage.getItem('auth_token');
    console.log('Loading token from localStorage:', savedToken);
  } else {
    // 优先从sessionStorage加载（会话存储）
    savedToken = sessionStorage.getItem('auth_token');
    console.log('Loading token from sessionStorage:', savedToken);
  }
  
  if (savedToken) {
    token = savedToken;
    window.token = savedToken;
    return token; // 返回实际的token值，而不仅仅是布尔值
  }
  console.warn('No token found in storage');
  return null;
}

// 清除token
function clearToken() {
  console.log('Clearing token');
  token = '';
  window.token = '';
  localStorage.removeItem('auth_token');
  localStorage.removeItem('remember_me');
  sessionStorage.removeItem('auth_token');
}

// 页面导航函数
function navigateTo(page) {
  // 隐藏所有页面
  document.querySelectorAll('.page').forEach(page => {
    page.classList.add('hidden');
  });
  
  // 显示指定页面
  document.getElementById(page).classList.remove('hidden');
  
  // 更新导航栏激活状态
  document.querySelectorAll('.nav-link').forEach(link => {
    link.classList.remove('active');
  });
  
  const activeLink = document.querySelector(`[data-page="${page}"]`);
  if (activeLink) {
    activeLink.classList.add('active');
  }
}

// 调试信息数组
let debugInfos = [];

// 调试面板过滤和排序选项
let debugFilterOptions = {
  method: '',
  status: '',
  keyword: '',
  sortBy: 'timestamp',
  sortOrder: 'desc'
};

// 添加调试信息
function addDebugInfo(info) {
  debugInfos.push(info);
  updateDebugPanel();
}

// 更新调试面板
function updateDebugPanel() {
  const debugContent = document.getElementById('debug-content');
  if (debugContent) {
    // 应用过滤器
    let filteredInfos = debugInfos.filter(info => {
      // 方法过滤
      if (debugFilterOptions.method && info.method !== debugFilterOptions.method) {
        return false;
      }
      
      // 状态过滤
      if (debugFilterOptions.status && 
          (!info.response || info.response.status.toString() !== debugFilterOptions.status)) {
        return false;
      }
      
      // 关键字过滤
      if (debugFilterOptions.keyword) {
        const keyword = debugFilterOptions.keyword.toLowerCase();
        const methodMatch = info.method.toLowerCase().includes(keyword);
        const urlMatch = info.url.toLowerCase().includes(keyword);
        const statusMatch = info.response && info.response.status.toString().includes(keyword);
        const bodyMatch = info.body && info.body.toLowerCase().includes(keyword);
        const responseMatch = info.response && JSON.stringify(info.response.data).toLowerCase().includes(keyword);
        
        if (!methodMatch && !urlMatch && !statusMatch && !bodyMatch && !responseMatch) {
          return false;
        }
      }
      
      return true;
    });
    
    // 应用排序
    filteredInfos.sort((a, b) => {
      let valueA, valueB;
      
      switch (debugFilterOptions.sortBy) {
        case 'method':
          valueA = a.method;
          valueB = b.method;
          break;
        case 'status':
          valueA = a.response ? a.response.status : 0;
          valueB = b.response ? b.response.status : 0;
          break;
        case 'timestamp':
        default:
          valueA = a.timestamp;
          valueB = b.timestamp;
          break;
      }
      
      if (typeof valueA === 'string') {
        valueA = valueA.toLowerCase();
        valueB = valueB.toLowerCase();
      }
      
      if (debugFilterOptions.sortOrder === 'asc') {
        return valueA > valueB ? 1 : -1;
      } else {
        return valueA < valueB ? 1 : -1;
      }
    });
    
    // 只保留最近的50条记录
    const recentInfos = filteredInfos.slice(-50);
    debugContent.innerHTML = recentInfos.map(info => {
      let requestDetails = '';
      if (info.body) {
        try {
          const body = JSON.parse(info.body);
          requestDetails += `<div class="debug-entry-body">
            <button class="debug-entry-toggle" onclick="toggleDebugDetail(this, 'body-${info.timestamp}')">显示请求体</button>
            <pre id="body-${info.timestamp}" style="display:none">${JSON.stringify(body, null, 2)}</pre>
          </div>`;
        } catch (e) {
          requestDetails += `<div class="debug-entry-body">
            <strong>请求体:</strong> ${info.body}
          </div>`;
        }
      }
      
      return `<div class="debug-entry">
        <div class="debug-entry-header">
          <span class="debug-entry-method ${info.method}">${info.method}</span>
          <span class="debug-entry-status status-${info.response ? info.response.status : 'N/A'}">${info.response ? info.response.status : 'N/A'}</span>
        </div>
        <div class="debug-entry-url">${info.url}</div>
        <div class="debug-entry-time">${new Date(info.timestamp).toLocaleString()}</div>
        <div class="debug-entry-details">
          <button class="debug-entry-toggle" onclick="toggleDebugDetail(this, 'details-${info.timestamp}')">显示详情</button>
          <div id="details-${info.timestamp}" style="display:none">
            ${requestDetails}
            <div class="debug-entry-response">
              <strong>响应:</strong>
              <button class="debug-entry-toggle" onclick="showDetailModal('${info.timestamp}')">查看完整响应</button>
              <pre>${(JSON.stringify(info.response?.data || info.error, null, 2) || '').substring(0, 200)}${(JSON.stringify(info.response?.data || info.error, null, 2) || '').length > 200 ? '...' : ''}</pre>
            </div>
          </div>
        </div>
      </div>`;
    }).join('');
    
    // 自动滚动到底部
    debugContent.scrollTop = debugContent.scrollHeight;
  }
}

// 切换调试详情显示
function toggleDebugDetail(button, elementId) {
  const element = document.getElementById(elementId);
  if (element.style.display === 'none') {
    element.style.display = 'block';
    button.textContent = '隐藏详情';
  } else {
    element.style.display = 'none';
    button.textContent = '显示详情';
  }
}

// 显示详细信息模态框
function showDetailModal(timestamp) {
  const info = debugInfos.find(i => i.timestamp === timestamp);
  if (!info) return;
  
  // 创建模态框
  const modal = document.createElement('div');
  modal.className = 'debug-modal';
  modal.id = 'debug-detail-modal';
  modal.innerHTML = `
    <div class="debug-modal-content">
      <div class="debug-modal-header">
        <h3>请求详情</h3>
        <button class="debug-modal-close" onclick="closeDetailModal()">&times;</button>
      </div>
      <div class="debug-modal-body">
        <h4>基本信息</h4>
        <p><strong>方法:</strong> ${info.method}</p>
        <p><strong>URL:</strong> ${info.url}</p>
        <p><strong>时间:</strong> ${new Date(info.timestamp).toLocaleString()}</p>
        <p><strong>状态:</strong> ${info.response ? info.response.status : 'N/A'}</p>
        
        <h4>请求头</h4>
        <pre class="debug-modal-pre">${JSON.stringify(info.headers, null, 2)}</pre>
        
        ${info.body ? `
        <h4>请求体</h4>
        <pre class="debug-modal-pre">${formatJsonString(info.body)}</pre>
        ` : ''}
        
        <h4>响应</h4>
        <pre class="debug-modal-pre">${formatJsonString(JSON.stringify(info.response?.data || info.error, null, 2))}</pre>
      </div>
    </div>
  `;
  
  document.body.appendChild(modal);
}

// 格式化JSON字符串
function formatJsonString(str) {
  try {
    return JSON.stringify(JSON.parse(str), null, 2);
  } catch (e) {
    return str;
  }
}

// 关闭详细信息模态框
function closeDetailModal() {
  const modal = document.getElementById('debug-detail-modal');
  if (modal) {
    modal.remove();
  }
}

// 清空调试信息
function clearDebugInfo() {
  debugInfos = [];
  updateDebugPanel();
}

// 更新过滤选项
function updateDebugFilter() {
  debugFilterOptions.method = document.getElementById('debug-filter-method').value;
  debugFilterOptions.status = document.getElementById('debug-filter-status').value;
  debugFilterOptions.keyword = document.getElementById('debug-filter-keyword').value;
  updateDebugPanel();
}

// 更新排序选项
function updateDebugSort() {
  debugFilterOptions.sortBy = document.getElementById('debug-sort-by').value;
  debugFilterOptions.sortOrder = document.getElementById('debug-sort-order').value;
  updateDebugPanel();
}

// 重置过滤器
function resetDebugFilter() {
  debugFilterOptions = {
    method: '',
    status: '',
    keyword: '',
    sortBy: 'timestamp',
    sortOrder: 'desc'
  };
  
  document.getElementById('debug-filter-method').value = '';
  document.getElementById('debug-filter-status').value = '';
  document.getElementById('debug-filter-keyword').value = '';
  document.getElementById('debug-sort-by').value = 'timestamp';
  document.getElementById('debug-sort-order').value = 'desc';
  
  updateDebugPanel();
}

// 切换调试面板显示状态
function toggleDebugPanel() {
  const debugPanel = document.getElementById('debug-panel');
  const toggleButton = document.getElementById('debug-panel-toggle');
  
  if (debugPanel && toggleButton) {
    // 使用独立的类名来控制调试面板的显示状态，避免与页面折叠冲突
    debugPanel.classList.toggle('debug-panel-open');
    toggleButton.textContent = debugPanel.classList.contains('debug-panel-open') ? '隐藏调试' : '显示调试';
  }
}

// 初始化调试面板
function initDebugPanel() {
  // 创建调试面板切换按钮
  const toggleButton = document.createElement('button');
  toggleButton.id = 'debug-panel-toggle';
  toggleButton.className = 'debug-toggle-btn';
  toggleButton.textContent = '显示调试';
  toggleButton.onclick = toggleDebugPanel;
  
  // 创建调试面板
  const debugPanel = document.createElement('div');
  debugPanel.id = 'debug-panel';
  debugPanel.className = 'debug-panel';
  debugPanel.innerHTML = `
    <div class="debug-panel-header">
      <h3>调试信息</h3>
      <div>
        <button onclick="clearDebugInfo()" class="debug-clear-btn">清空</button>
        <button onclick="toggleDebugPanel()">×</button>
      </div>
    </div>
    
    <div class="debug-search-box">
      <select id="debug-filter-method" onchange="updateDebugFilter()">
        <option value="">所有方法</option>
        <option value="GET">GET</option>
        <option value="POST">POST</option>
        <option value="PUT">PUT</option>
        <option value="DELETE">DELETE</option>
      </select>
      
      <select id="debug-filter-status" onchange="updateDebugFilter()">
        <option value="">所有状态</option>
        <option value="200">200</option>
        <option value="400">400</option>
        <option value="401">401</option>
        <option value="403">403</option>
        <option value="404">404</option>
        <option value="500">500</option>
      </select>
      
      <input type="text" id="debug-filter-keyword" placeholder="搜索关键字..." oninput="updateDebugFilter()">
      
      <div class="debug-search-controls">
        <select id="debug-sort-by" onchange="updateDebugSort()">
          <option value="timestamp">时间</option>
          <option value="method">方法</option>
          <option value="status">状态</option>
        </select>
        
        <select id="debug-sort-order" onchange="updateDebugSort()">
          <option value="desc">降序</option>
          <option value="asc">升序</option>
        </select>
        
        <button onclick="resetDebugFilter()">重置</button>
      </div>
    </div>
    
    <div class="debug-panel-content">
      <div id="debug-content"></div>
    </div>
  `;
  
  // 添加到页面
  document.body.appendChild(toggleButton);
  document.body.appendChild(debugPanel);
}

// 将数据渲染为表格
function renderTable(data, containerId) {
  const container = document.getElementById(containerId);
  if (!container) return;
  
  if (!data || data.length === 0) {
    container.innerHTML = '<p class="info">暂无数据</p>';
    return;
  }
  
  // 获取所有可能的列名
  const allKeys = new Set();
  data.forEach(item => {
    Object.keys(item).forEach(key => allKeys.add(key));
  });
  
  // 创建表头
  let tableHTML = '<table class="data-table"><thead><tr>';
  allKeys.forEach(key => {
    tableHTML += `<th>${key}</th>`;
  });
  tableHTML += '</tr></thead><tbody>';
  
  // 创建表体
  data.forEach(item => {
    tableHTML += '<tr>';
    allKeys.forEach(key => {
      const value = item[key];
      tableHTML += `<td>${value !== null && value !== undefined ? value : ''}</td>`;
    });
    tableHTML += '</tr>';
  });
  
  tableHTML += '</tbody></table>';
  container.innerHTML = tableHTML;
}